﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Clarendon.AzureBilling.Library
{
    /// <summary>
    /// This class returns the initial service list for the Azure subscription
    /// </summary>
    public class ServiceListRequester : RequestAzureService
    {
        /// <summary>
        /// Default constructor for ServiceListRequester class
        /// </summary>
        public ServiceListRequester(ServiceManager manager) : base(manager)
        {
            Parser = new XmlParseServiceList();
        }
        /// <summary>
        /// This method is a callback to populate the services into a hostedservices list
        /// </summary>
        public override void Populate(HttpWebResponse response)
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                Manager.HostedServices = Parser.ParseXmlString<List<HostedService>>(reader.ReadToEnd());
                Trace.WriteLine(String.Format("Azure returned {0} hosted services for subscription id {1}", Manager.HostedServices.Count, Manager.SubscriptionId));
                ReleaseSemaphore();
            }
        }

        /// <summary>
        /// Give a list of services using the RESTful Azure Management API
        /// </summary>
        public override void MakeServiceRequest()
        {
            ServiceManagementRequest serviceManager = GetServiceManagementRequest("hostedservices");
            QueryManager.MakeASyncRequest(serviceManager, Manager.CertificateFile, 
                new ServiceManager.AsyncResponseParser(Populate));
        }
    }
}
